package com.ssb.admin.common.utils;

import io.netty.util.internal.StringUtil;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class TreeBuilder {

    public static List<TreeNode> buildListToTree(List<TreeNode> nodes) {
        if (nodes == null) {
            return null;
        }
        List<TreeNode> roots = findRoots(nodes);
        @SuppressWarnings("unchecked")
        List<TreeNode> notRoots = (List<TreeNode>) CollectionUtils.subtract(nodes, roots);
        for (TreeNode root : roots) {
            List<TreeNode> childrenNodes = findChildren(root, notRoots);
            root.setChildren(childrenNodes);

        }
        return roots;
    }

    private static List<TreeNode> findRoots(List<TreeNode> allTreeNodes) {
        List<TreeNode> results = new ArrayList<>();
        for (TreeNode treeNode : allTreeNodes) {
            boolean isRoot = true;
            for (TreeNode comparedOne : allTreeNodes) {
                if (treeNode.getParentId().equals(comparedOne.getNodeId())) {
                    isRoot = false;
                    break;
                }
            }
            if (isRoot) {
                results.add(treeNode);
            }
        }
        return results;
    }

    private static List<TreeNode> findChildren(TreeNode root, List<TreeNode> allTreeNodes) {
        List<TreeNode> children = new ArrayList<>();


        for (TreeNode comparedOne : allTreeNodes) {
            if (comparedOne.getParentId().equals(root.getNodeId())) {
                children.add(comparedOne);
                String fullPath = root.getPath()+comparedOne.getPath();
                // 子模块默认展开路径
                if(comparedOne.getIsDefault()){
                    root.setRedirect(fullPath);
                }
            }
        }
        @SuppressWarnings("unchecked")
        List<TreeNode> notChildren = (List<TreeNode>) CollectionUtils.subtract(allTreeNodes, children);
        for (TreeNode child : children) {
            List<TreeNode> tmpChildren = findChildren(child, notChildren);
            if (tmpChildren.size()>0){
                child.setChildren(tmpChildren);
            }else {
                // json输出忽略
                child.setChildren(null);
                // 重置子模块url 配合前端 叶子模块url去掉 /
                if (!StringUtil.isNullOrEmpty(child.getPath())) {
                    child.setPath(child.getPath().replace("/", ""));
                }
            }
        }
        return children;
    }
}
